package com.eversec.view.panel;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListModel;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;

import com.eversec.util.ftp.EncryptConstant;
import com.eversec.util.ftp.FtpDataOper;
import com.eversec.util.ftp.FtpXmlUtil;
import com.eversec.view.render.ListCellRenderer;

/**
 * 文件解密TabPanel界面
 * 
 * @author lilizhao
 * 
 */
public class FileEncrypationPanel extends JPanel {

	private static final long serialVersionUID = 5912624209290677682L;

	// north panel组件
	private JLabel catalogLabel;
	private JTextField catalogfField;
	private JButton catalogBroswerButton;

	// center panel组件
	private JList fileList;
	private JProgressBar fileProgressBar;

	// sourth panel组件
	private JRadioButton okRadioButton;
	private JRadioButton errRadioButton;
	private JRadioButton xmlRadioButton;
	private JRadioButton allRadioButton;
	private JButton decryptButton;
	private JButton clearButton;
	private ButtonGroup radioGroup;

	public FileEncrypationPanel() {
		initComponents();
		initListener();
	}

	/**
	 * 初始化组件
	 */
	private void initComponents() {
		setLayout(new BorderLayout());
		setBackground(new Color(252, 252, 252));

		JPanel northPanel = initNorthPanel();
		JPanel centerPanel = initCenterPanel();
		JPanel sourthPanel = initSourthPanel();

		add(northPanel, BorderLayout.NORTH);
		add(centerPanel, BorderLayout.CENTER);
		add(sourthPanel, BorderLayout.SOUTH);
	}

	/**
	 * 初始化north panel
	 * 
	 * @return
	 */
	private JPanel initNorthPanel() {
		JPanel northPanel = new JPanel();
		northPanel.setLayout(new GridBagLayout());
		northPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4),
				BorderFactory.createEtchedBorder()));
		northPanel.setOpaque(false);

		catalogLabel = new JLabel("目录：");
		catalogfField = new JTextField();
		catalogfField.setEditable(false);
		catalogfField.setEnabled(false);
		catalogfField.setBorder(BorderFactory.createLineBorder(Color.BLACK));
		catalogBroswerButton = new JButton("浏览");

		northPanel.add(catalogLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, //
				GridBagConstraints.WEST, GridBagConstraints.NONE, //
				new Insets(5, 5, 5, 0), 0, 0));
		northPanel.add(catalogfField, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, //
				GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, //
				new Insets(5, 0, 5, 0), 0, 0));
		northPanel.add(catalogBroswerButton, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0,//
				GridBagConstraints.WEST, GridBagConstraints.NONE, //
				new Insets(5, 0, 5, 0), 0, 0));

		return northPanel;
	}

	/**
	 * 初始化center panel
	 * 
	 * @return
	 */
	private JPanel initCenterPanel() {
		JPanel centerPanel = new JPanel();
		centerPanel.setLayout(new BorderLayout());

		fileList = new JList();
		// 设置先纵向后横向滚动
		fileList.setLayoutOrientation(JList.VERTICAL_WRAP);
		fileList.setFixedCellHeight(16);
		fileList.setFixedCellWidth(250);
		// VERTICAL 在单个列中垂直布置单元。
		// HORIZONTAL_WRAP 水平布置单元，根据需要将单元包装到新行中。如果 visibleRowCount 属性小于等于
		// 0，则包装由该列表的宽度确定；否则，以确保列表中 visibleRowCount 行的方式进行包装。
		// VERTICAL_WRAP 垂直布置单元，根据需要将单元包装到新列中。如果 visibleRowCount 属性小于等于
		// 0，则包装由该列表的宽度确定；否则，在 visibleRowCount 行进行包装。
		fileList.setVisibleRowCount(0);
		fileList.setCellRenderer(new ListCellRenderer());
		// fileList.addMouseListener(new DataListMouseAdapter(fileList));
		JScrollPane dataScrollPane = new JScrollPane(fileList, JScrollPane.VERTICAL_SCROLLBAR_NEVER,
				JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		dataScrollPane.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2),
				BorderFactory.createEtchedBorder()));
		// dataScrollPane.setOpaque(false);

		fileProgressBar = new JProgressBar();
		fileProgressBar.setOrientation(JProgressBar.HORIZONTAL);
		fileProgressBar.setMinimum(0);
		fileProgressBar.setMaximum(100);
		fileProgressBar.setValue(0);
		fileProgressBar.setStringPainted(true);
		fileProgressBar.setBackground(Color.pink);
		fileProgressBar.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));

		centerPanel.add(dataScrollPane, BorderLayout.CENTER);
		// centerPanel.add(fileProgressBar, BorderLayout.SOUTH);
		centerPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4),
				BorderFactory.createEtchedBorder()));
		centerPanel.setOpaque(false);
		return centerPanel;
	}

	/**
	 * 初始化sourth panel
	 * 
	 * @return
	 */
	private JPanel initSourthPanel() {
		JPanel sourthPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));

		Box mainBox = Box.createHorizontalBox();

		okRadioButton = new JRadioButton("ok类文件");
		errRadioButton = new JRadioButton("err类文件");
		xmlRadioButton = new JRadioButton("xml类文件");
		allRadioButton = new JRadioButton("有效文件");
		okRadioButton.setOpaque(false);
		errRadioButton.setOpaque(false);
		xmlRadioButton.setOpaque(false);
		allRadioButton.setOpaque(false);

		decryptButton = new JButton("解密");
		clearButton = new JButton("清空");

		radioGroup = new ButtonGroup();
		radioGroup.add(okRadioButton);
		radioGroup.add(errRadioButton);
		radioGroup.add(xmlRadioButton);
		radioGroup.add(allRadioButton);

		mainBox.add(okRadioButton);
		mainBox.add(errRadioButton);
		mainBox.add(xmlRadioButton);
		mainBox.add(allRadioButton);
		mainBox.add(decryptButton);
		mainBox.add(clearButton);

		sourthPanel.add(mainBox);

		sourthPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4),
				BorderFactory.createEtchedBorder()));
		sourthPanel.setOpaque(false);
		return sourthPanel;
	}

	/**
	 * 添加监听
	 */
	private void initListener() {
		catalogBroswerButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JFileChooser fileChooser = new JFileChooser();
				fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				fileChooser.setMultiSelectionEnabled(false);
				int preesButton = fileChooser.showOpenDialog(FileEncrypationPanel.this);
				if (preesButton == JFileChooser.APPROVE_OPTION) {
					File selectedFile = fileChooser.getSelectedFile();
					catalogfField.setText(fileChooser.getSelectedFile().getAbsolutePath());
					if (selectedFile != null) {
						fileList.setListData(selectedFile.listFiles());
					}
				}

			}
		});
		fileList.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				// 点击鼠标左键并且选中文件不为空
				if (e.getButton() == MouseEvent.BUTTON1 && fileList.getSelectedValues().length != 0) {
					// 取消单选按钮的选中状态
					radioGroup.clearSelection();
				}
			}
		});
		okRadioButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				setSelectFiles(new String[] { ".ok" });
			}
		});
		errRadioButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				setSelectFiles(new String[] { ".err" });
			}
		});
		xmlRadioButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				setSelectFiles(new String[] { ".xml" });
			}
		});
		allRadioButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				setSelectFiles(new String[] { ".ok", ".err", "xml" });
			}
		});
		decryptButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				int[] selectedIndices = fileList.getSelectedIndices();
				if (selectedIndices.length == 0) {
					JOptionPane.showMessageDialog(FileEncrypationPanel.this, "请选择有效文件", "", JOptionPane.ERROR_MESSAGE);
				} else {
					// 步骤1 先对需要进行解密的合法文件进行统计
					List<File> vaildFiles = new ArrayList<File>();
					for (int selectedIndex : selectedIndices) {
						File selectFile = (File) fileList.getModel().getElementAt(selectedIndex);
						// 如果选中的是文件就全部解密
						// 此处不递归遍历所有文件，因为担心选中的是根目录
						countValildFile(vaildFiles, selectFile);
					}
					// 步骤2 对统计的文件进行解密
					if (vaildFiles.size() == 0) {
						JOptionPane.showMessageDialog(FileEncrypationPanel.this, "请选择有效文件", "", JOptionPane.ERROR_MESSAGE);
					} else {
//						fileProgressBar.setValue(0);
						for (int i = 0; i < vaildFiles.size(); i++) {
							File srcFile = vaildFiles.get(i);
							String content = FtpXmlUtil.readFile(srcFile);
							String xmlData = new FtpDataOper().ftpFileOper(content, EncryptConstant.aesKey, EncryptConstant.aesOffsets,
									EncryptConstant.hashcode, EncryptConstant.messageKey);
							File targetFile = new File(srcFile.getAbsolutePath().substring(0, srcFile.getAbsolutePath().lastIndexOf(".")) + ".src");
							String formatXML = FtpXmlUtil.formatXML(xmlData);
							FtpXmlUtil.writeFile(targetFile, formatXML);
						}
						JOptionPane.showMessageDialog(FileEncrypationPanel.this, "完成解密！", "", JOptionPane.INFORMATION_MESSAGE);
					}
				}
			}

			/**
			 * 统计所有需要的进行解密的文件
			 * 
			 * @param vaildFiles
			 * @param selectFile
			 */
			private void countValildFile(List<File> vaildFiles, File selectFile) {
				if (selectFile.isDirectory()) {
					int currentfileLevel = StringUtils.countMatches(selectFile.getAbsolutePath(), File.separator);
					int listFileLevel = StringUtils.countMatches(catalogfField.getText(), File.separator);

					if (currentfileLevel - listFileLevel < 5) {
						File[] listFiles = selectFile.listFiles();
						for (File file : listFiles) {
							if (file.isDirectory()) {
								countValildFile(vaildFiles, file);
							} else if (file.isFile()) {
								String fileName = file.getName().toLowerCase();
								if (fileName.endsWith(".ok") || fileName.endsWith(".err") || fileName.endsWith(".xml")) {
									vaildFiles.add(file);
								}
							}
						}
					}
				} else if (selectFile.isFile()) {
					String fileName = selectFile.getName().toLowerCase();
					if (fileName.endsWith(".ok") || fileName.endsWith(".err") || fileName.endsWith(".xml")) {
						vaildFiles.add(selectFile);
					}
				}
			}
		});
		clearButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				catalogfField.setText("");
				fileList.setListData(new File[] {});
			}
		});
	}

	/**
	 * 根据传入的后缀设置选中的文件
	 * 
	 * @param fileSuffixs
	 */
	private void setSelectFiles(String[] fileSuffixs) {
		ArrayList<Integer> selectList = new ArrayList<Integer>();

		ListModel listModel = fileList.getModel();
		for (int i = 0; i < listModel.getSize(); i++) {
			String listName = listModel.getElementAt(i).toString();
			for (String fileSuffix : fileSuffixs) {
				if (listName.toLowerCase().endsWith(fileSuffix)) {
					selectList.add(i);
				}
			}
		}

		fileList.setSelectedIndices(ArrayUtils.toPrimitive(selectList.toArray(new Integer[selectList.size()])));
	}

}
